#!/usr/bin/python
# coding=utf8
#
# Copyright (C) 2011 XNData contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


__author__ = "zhangchitc@gmail.com"


import urllib2, urllib
import re, json
import time, datetime
import xndata.client
import xndata.data.status

class StatusUrlMgr:

    @staticmethod
    def status_list_url (user_id, cur_page):
        return "http://status.renren.com/GetSomeomeDoingList.do?userId=%s&curpage=%d" % (
                user_id, cur_page)


class StatusPageFetcher:

    @staticmethod
    def fetch_status_list_page (opener, user_id, cur_page):
        request = urllib2.Request (StatusUrlMgr.status_list_url (
                user_id, cur_page))
        return opener.open (request).read ()


class StatusPageParser:

    @staticmethod
    def get_total_status (html):
        json_obj = json.loads (html)
        return json_obj[u"count"]
  
    @staticmethod
    def get_status_list (html, user_id, cur_page):
        json_obj = json.loads (html)
        json_list = json_obj[u"doingArray"]
        status_list = xndata.data.status.StatusList (
                user_id = user_id, cur_page = cur_page)
        for json_status in json_list:
            author_name = str (json_status["name"].encode ("utf-8"))
            author_id = str (json_status["userId"])
            status_id = str (int (json_status["id"]))
            content = str (json_status["content"].encode ("utf-8"))
            dtime = str (json_status["dtime"].encode ("utf-8"))
            pub_time_struct = time.strptime (dtime, "%Y-%m-%d %H:%M:%S")
            pub_time = datetime.datetime (*pub_time_struct[0:5])
            status = xndata.data.status.Status (
                    status_id = status_id, content = content, 
                    author_id = author_id, author_name = author_name,
                    pub_time = pub_time)
            status_list.addStatus (status)
        return status_list


if __name__ == "__main__":
    client = xndata.client.XNClient ("zhangchitc@gmail.com", "aaaaaaaa")
    html = StatusPageFetcher.fetch_status_list_page (
        client.opener, "247780420", 0)
    print html
    StatusPageParser.get_status_list (html, 0, 0)
